package pl.edu.pb.wi.cookbook.controller;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import pl.edu.pb.wi.cookbook.entity.Category;
import pl.edu.pb.wi.cookbook.entity.Cookbook;
import pl.edu.pb.wi.cookbook.entity.Recipe;
import pl.edu.pb.wi.cookbook.form.AddToCookbookForm;
import pl.edu.pb.wi.cookbook.service.CategoryService;
import pl.edu.pb.wi.cookbook.service.CookbookService;
import pl.edu.pb.wi.cookbook.service.RecipeService;
import pl.edu.pb.wi.cookbook.session.UserSession;

@Controller
@RequestMapping("/recipe")
public class RecipeController {
    private static final Logger log = Logger.getLogger(RecipeController.class
            .getName());

    private RecipeService recipeService;
    private CategoryService categoryService;
    private CookbookService cookbookService;
    private UserSession userSession;

    @Autowired
    public RecipeController(RecipeService recipeService,
            CategoryService categoryService, CookbookService cookbookService,
            UserSession userSession) {
        this.recipeService = recipeService;
        this.categoryService = categoryService;
        this.cookbookService = cookbookService;
        this.userSession = userSession;
    }

    @RequestMapping("list")
    public String list(Model model) {
        try {
            Category current = categoryService.getFirstCategory();
            model.addAttribute("currentCat", current);

            model.addAttribute(
                    "categories",
                    current != null ? categoryService
                            .getCategoryChildren(current) : null);
            model.addAttribute(
                    "recipes",
                    current != null ? recipeService.getRecipesFromCategory(
                            current, false) : null);
        } catch (Exception ex) {
            log.info(String.format("Problem with recipe list. Exception: %s",
                    ex.getMessage()));

            model.addAttribute(
                    "errorMsgs",
                    Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));

            return "message";
        }

        return "recipe/list";
    }

    @RequestMapping("list/{catId}")
    public String listById(@PathVariable("catId")
    Long catId, Model model) {
        try {
            Category current = categoryService.getCategory(catId);
            if (current != null) {
                model.addAttribute("currentCat", current);
                model.addAttribute("categories",
                        categoryService.getCategoryChildren(current));
                model.addAttribute("recipes",
                        recipeService.getRecipesFromCategory(current, false));
            } else {
                return "redirect:/recipe/list";
            }
        } catch (Exception ex) {
            log.info(String.format("Problem with recipe list. Exception: %s",
                    ex.getMessage()));

            model.addAttribute(
                    "errorMsgs",
                    Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));

            return "message";
        }

        return "recipe/list";
    }

    @RequestMapping("rate/{recId}/{value}")
    public String rate(@PathVariable("recId")
    Long recId, @PathVariable("value")
    Integer value, Model model) {

        if (value == null) {
            model.addAttribute("errorMsgs",
                    Arrays.asList(new String[] { "Nieprawidłowa wartość." }));

            return "messages";
        }

        try {
            Recipe current = recipeService.getRecipe(recId);
            if (current != null) {
                recipeService.rateRecipe(userSession.getUser(), current, value);

                model.addAttribute(
                        "infoMsgs",
                        Arrays.asList(new String[] { "Twoja ocena została zapisana." }));
            } else {
                model.addAttribute("errorMsgs", Arrays
                        .asList(new String[] { "Nieprawidłowy przepis." }));

                return "messages";
            }
        } catch (Exception ex) {
            log.info(String.format("Problem with recipe list. Exception: %s",
                    ex.getMessage()));

            model.addAttribute(
                    "errorMsgs",
                    Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));

            return "message";
        }

        return String.format("forward:/recipe/%s", recId);
    }

    // @RequestMapping("rate/plus/{Id}")
    // public String rateplus(@PathVariable("Id")
    // Long Id, Model model) {
    // try {
    // Recipe current = recipeService.getRecipe(Id);
    // if (current != null) {
    // recipeService.rateRecipe(userSession.getUser(), current, 1);
    // if (userSession.getUser() != null) {
    // List<Cookbook> userCookbooksWithoutRec = cookbookService
    // .getUsersCookbooksWithoutRecipe(
    // userSession.getUser(), current);
    // model.addAttribute("recipe", current);
    // model.addAttribute("cookbooksWithoutThisRecipe",
    // userCookbooksWithoutRec);
    // model.addAttribute("form", new AddToCookbookForm());
    // model.addAttribute(
    // "israted",
    // recipeService.isRecipeRatedByUser(
    // userSession.getUser(), current));
    // }
    // } else {
    // model.addAttribute("errorMsgs", Arrays
    // .asList(new String[] { "Nieprawidłowy przepis." }));
    //
    // return "messages";
    // }
    // } catch (Exception ex) {
    // log.info(String.format("Problem with recipe list. Exception: %s",
    // ex.getMessage()));
    //
    // model.addAttribute(
    // "errorMsgs",
    // Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));
    //
    // return "message";
    // }
    //
    // return String.format("redirect:/recipe/show/", Id);
    // }

    // @RequestMapping("rate/minus/{Id}")
    // public String rateminus(@PathVariable("Id")
    // Long Id, Model model) {
    // try {
    // Recipe current = recipeService.getRecipe(Id);
    //
    // if (current != null) {
    // recipeService.rateRecipe(userSession.getUser(), current, -1);
    //
    // if (userSession.getUser() != null) {
    // List<Cookbook> userCookbooksWithoutRec = cookbookService
    // .getUsersCookbooksWithoutRecipe(
    // userSession.getUser(), current);
    // model.addAttribute(
    // "israted",
    // recipeService.isRecipeRatedByUser(
    // userSession.getUser(), current));
    // model.addAttribute("cookbooksWithoutThisRecipe",
    // userCookbooksWithoutRec);
    // model.addAttribute("form", new AddToCookbookForm());
    // model.addAttribute("recipe", current);
    // }
    // } else {
    // model.addAttribute("errorMsgs", Arrays
    // .asList(new String[] { "Nieprawidłowy przepis." }));
    //
    // return "messages";
    // }
    // } catch (Exception ex) {
    // log.info(String.format("Problem with recipe list. Exception: %s",
    // ex.getMessage()));
    //
    // model.addAttribute(
    // "errorMsgs",
    // Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));
    //
    // return "message";
    // }
    //
    // return String.format("redirect:/recipe/show/", Id);
    // }

    @RequestMapping("{recipeId}")
    public String show(@PathVariable("recipeId")
    Long recipeId, Model model) {
        try {
            Recipe recipe = recipeService.getRecipe(recipeId);

            if (recipe == null)
                return "redirect:/recipe/list";

            model.addAttribute("recipe", recipe);

            if (userSession.getUser() != null) {
                List<Cookbook> userCookbooksWithoutRec = cookbookService
                        .getUsersCookbooksWithoutRecipe(userSession.getUser(),
                                recipe);

                model.addAttribute("cookbooksWithoutThisRecipe",
                        userCookbooksWithoutRec);
                model.addAttribute("form", new AddToCookbookForm());
            }
        } catch (Exception ex) {
            log.info(String.format("Problem with recipe. Exception: %s",
                    ex.getMessage()));

            model.addAttribute(
                    "errorMsgs",
                    Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));

            return "message";
        }

        return "recipe/show";
    }
}
